package action
import (
	"signaling/src/comerrors"
	"signaling/src/framework"
	"encoding/json"
	"net/http"
	"strconv"
	"fmt"
)

type pullAction struct {}

func NewPullAction () *pullAction {
	return &pullAction{}
}

type xrtcPullReq struct {
	Cmdno int `json:"cmdno"`
	Uid uint64 `json:"uid"`
	StreamName string `json:"stream_name"`
	Audio int `json:"audio"`
	Video int `json:"video"`
	IsDtls int `json:"is_dtls"`
	Mode string `json:"mode"`

}
type xrtcPullResp struct {

	ErrNo int `json:"err_no"`
	ErrMsg string `json:"err_msg"`
	Offer string `json:"offer"`
}
type pullData struct {
	Type string `json:"type"`
	Sdp string `json:"sdp"`

}

func (* pullAction) Execute (w http.ResponseWriter, cr *framework.ComRequest){
	r :=cr.R
	//uid
	var strUid string
	if values,ok := r.Form["uid"];ok {

		strUid = values[0]
	}
	uid , err := strconv.ParseUint(strUid,10,64)
	if err != nil ||uid <=0 {
		cerr := comerrors.New(comerrors.ParamErr,"parse uid error:"+ err.Error())
		writeJsonErrorResponse(cerr,w,cr)
		return 
	}

	//streamName
	var streamName string
	if values,ok := r.Form["streamName"]; ok {
		streamName = values[0]
	}
	if "" == streamName {
		cerr := comerrors.New(comerrors.ParamErr,"streamName is null")
		writeJsonErrorResponse(cerr,w,cr)
		return
	}
	//audio 

	 var strAudio string
	 var audio int
	 if values ,ok := r.Form["audio"];ok {
		strAudio = values[0]

	 }
	 if "" == strAudio || "0" == strAudio {
		audio = 0
	 } else {
		audio = 1 
	 }
	 //video
	 var strVideo string
	 var video int
	 if values ,ok := r.Form["video"];ok {
		strVideo = values[0]
	 }
	 if "" == strVideo || "0" == strVideo {
		video = 0
	 } else {
		video = 1 
	 }
	   //dtls
	 var strDtls string
	 var isDtls int
	 if values ,ok := r.Form["isDtls"];ok {
		strDtls = values[0]
	 }
	 if "" == strDtls || "0" == strDtls {
		isDtls = 0
	 } else {
		isDtls = 1 
	 }

	  //Mode
	var mode string
	if values,ok := r.Form["mode"]; ok {
		mode = values[0]
	}
	if "" == mode {
		cerr := comerrors.New(comerrors.ParamErr,"mode is null")
		writeJsonErrorResponse(cerr,w,cr)
		return
	}
	//  fmt.Println(uid,streamName,audio,video)
	req := xrtcPullReq{

		Cmdno:CMDNO_PULL,
		Uid:uid,
		StreamName:streamName,
		Audio:audio,
		Video:video,
		IsDtls:isDtls,
		Mode:mode,

	}
	fmt.Printf("%+v\n",req)

	var resp xrtcPullResp
	err = framework.Call("xrtc",req, &resp,cr.LogId)
	//fmt.Printf("%+v\n",resp)
	//将数据返回给浏览器
	if err != nil {

		cerr := comerrors.New(comerrors.NetworkErr,"backend process error:"+ err.Error())
		writeJsonErrorResponse(cerr,w,cr)
		return
	}
	if resp.ErrNo != 0 {

		
		cerr := comerrors.New(comerrors.NetworkErr,
			fmt.Sprintf("backend process error:"+ err.Error()))
		writeJsonErrorResponse(cerr,w,cr)
		return
	}
	//构造http 响应体

	httpResp := comHttpResp{
		ErrNo : 0,
		ErrMsg: "success",
		Data:pullData{
			Type: "offer",
			Sdp: resp.Offer,
		},
	}

	b,  _  := json.Marshal(httpResp)
	cr.Logger.AddNotice("resp", string(b))
	w.Write(b)
}